<?php

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\Express as ExpressModel;
use app\api\model\OrderGoods as OrderGoodsModel;
use app\api\model\OrderRefund as OrderRefundModel;
use app\store\model\OrderRefund as OrderRefundModel1;
use app\common\model\Wxapp as WxappModel;
use app\common\library\wechat\WxSubMsg;
use app\api\model\Order as OrderModel;
/**
 * 订单售后服务
 * Class service
 * @package app\api\controller\user\order
 */
class Refund extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 用户售后单列表
     * @param int $state
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($state = -1)
    {
        $model = new OrderRefundModel;
        $list = $model->getList($this->user['user_id'], (int)$state);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 申请售后
     * @param $order_goods_id
     * @return array
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function apply($order_goods_id)
    {
        // dump($order_goods_id);die;
        // 订单商品详情
        $goods = OrderGoodsModel::detail($order_goods_id);
        
        if (isset($goods['refund']) && !empty($goods['refund'])) {
            return $this->renderError('当前订单已申请售后');
        }
        if (!$this->request->isPost()) {
            return $this->renderSuccess(['detail' => $goods]);
        }
        $order = DB("order")->where("order_id",$goods['order_id'])->find();
        if ($order['receipt_status'] == 20) {
            return $this->renderError('当前订单已就诊');
        }
        // dump($order['receipt_status']);die;
        // 新增售后单记录
        $model = new OrderRefundModel;
        $model1 = OrderModel::getUserOrderDetail($goods['order_id'], $this->user['user_id']);
        if ($order_refund_id = $model->apply($this->user, $goods, $this->request->post())) {
            // 新增直接操作退款
            $this->receipt($order_refund_id);
            // 开始发送消息
            // 获取小程序配置
            $wxappId = "10001";
            $wxConfig = WxappModel::getWxappCache($wxappId);
            // 请求微信api执行发送
            $WxSubMsg = new WxSubMsg($wxConfig['app_id'], $wxConfig['app_secret']);
            $params = [
                'touser' => DB("user")->where("user_id", $model1['user_id'])->value('open_id'), // 获取 open_id
                'template_id' => 'E3w69uDbrXTpAIJ036bmDWPQzSrpAf2GAkxKD2rgXMI',
                'page' => '', // 小程序页面路径，可根据需要填写
                'data' => [
                    'name1' => [
                        'value' => DB("user_jiuzhen")->where("jiuzhen_id", $model1['goods'][0]['jiuzhen_id'])->value('name') ?: '未填写姓名'
                    ],
                    'name6' => [
                        'value' => $model1['goods'][0]['goods_name'] ?: '未填写商品名称'
                    ],
                    'thing2' => [
                        'value' => DB("category")
                            ->where('category_id', DB("goods")->where('goods_id', $model1['goods'][0]['goods_id'])->value('category_id'))
                            ->value('name') ?: '未分类'
                    ],
                    'date4' => [
                        'value' => $model1['goods'][0]['jiuzhen_day'] ?: '无预约日期'
                    ],
                    'thing5' => [
                        'value' => "您好，您已取消预约挂号"
                    ],
                ],
            ];
            $WxSubMsg->sendTemplateMessage($params);
            return $this->renderSuccess([], '提交成功');
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }
    // 新增直接操作退款
    public function receipt($order_refund_id)
    {
        $model = OrderRefundModel1::detail($order_refund_id); 
        $refund['refund_money'] = DB("order")->where('order_id',$model['order_id'])->find()['pay_price'];
        // 修改订单状态开始
        DB("order")->where('order_id',$model['order_id'])->update(['order_status'=>20]);
        // 修改订单状态结束
        if ($model->receipt($refund)) {
            // return $this->renderSuccess([], '提交成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }
    /**
     * 售后单详情
     * @param $order_refund_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function detail($order_refund_id)
    {
        // 售后单详情
        $detail = OrderRefundModel::detail([
            'user_id' => $this->user['user_id'],
            'order_refund_id' => $order_refund_id
        ]);
        if (empty($detail)) {
            return $this->renderError('售后单不存在');
        }
        // 物流公司列表
        $expressList = ExpressModel::getAll();
        return $this->renderSuccess(compact('detail', 'expressList'));
    }

    /**
     * 用户发货
     * @param $order_refund_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delivery($order_refund_id)
    {
        // 售后单详情
        $model = OrderRefundModel::detail([
            'user_id' => $this->user['user_id'],
            'order_refund_id' => $order_refund_id
        ]);
        if ($model->delivery($this->postData())) {
            return $this->renderSuccess([], '操作成功');
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }

}